package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.model.request.ProductUnitInfoForm;
import com.wing.product.model.response.ProductUnitInfoVO;
import com.wing.product.service.ProductUnitService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.pulsar.shade.org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "Admin-产品单位管理", tags = "#/product/productUnit")
@RestController("productUnitController")
@RequestMapping("product/admin/productUnit")
@RequiredArgsConstructor
public class ProductUnitController {

    private final ProductUnitService productUnitService;

    @Autowired
    private PlatformClient platformClient;


    @ApiOperation(value = "查询所有产品单位", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductUnitInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , String name
            , Long productType
            , @RequestParam(defaultValue = "enterprise") ProductUnitInfo.DataSourceType dataSourceType
    ) {

        Page<ProductUnitInfo> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        paramMap.put("name", name);
        if (null != productType) {
            paramMap.put("productType", productType);
        }
        paramMap.put("dataSourceType", ProductUnitInfo.DataSourceType.enterprise.getValue());
        IPage<ProductUnitInfoVO> list = productUnitService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加产品单位", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductUnitInfoForm.Add.class) ProductUnitInfoForm productUnitInfoForm) {

        if (productUnitInfoForm.getIsBaseUnit()) {
            Integer count = productUnitService.count(new QueryWrapper<ProductUnitInfo>().eq("product_type", productUnitInfoForm.getProductType()).eq("is_base_unit", true));
            if (count > 0) {
                return JsonResult.fail("该类型下基础单位已经存在");
            }
        }
        if (productUnitService.add(productUnitInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改产品单位", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductUnitInfoForm.Update.class) ProductUnitInfoForm productUnitInfoForm) {

        if (productUnitInfoForm.getIsBaseUnit()) {
            Integer count = productUnitService.count(new QueryWrapper<ProductUnitInfo>().eq("product_type", productUnitInfoForm.getProductType()).eq("is_base_unit", true));
            if (count > 0) {
                return JsonResult.fail("该类型下基础单位已经存在,不能再设置为基础单位");
            }
        }
        ProductUnitInfo productUnitInfo = productUnitService.getById(productUnitInfoForm.getId());
        if (productUnitInfo == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductUnitInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productUnitInfoForm, productUnitInfo, copyOptions);
        if (productUnitService.updateById(productUnitInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除产品单位", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productUnitId", value = "产品单位id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productUnitId) {

        if (productUnitService.removeById(productUnitId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "启用产品单位", notes = "启用")
    @com.wing.common.annotation.RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(ProductUnitInfoForm.Add.class) ProductUnitInfoForm productBrandForm) {

        ProductUnitInfo productUnitInfo = new ProductUnitInfo();
        productUnitInfo.setId(productBrandForm.getId());
        productUnitInfo.setIsDeleted(true);
        if (productUnitService.updateById(productUnitInfo)) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用产品单位", notes = "停用")
    @com.wing.common.annotation.RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductUnitInfoForm.Add.class) ProductUnitInfoForm productUnitInfoForm) {

        ProductUnitInfo productUnitInfo = new ProductUnitInfo();
        productUnitInfo.setId(productUnitInfoForm.getId());
        productUnitInfo.setIsDeleted(false);
        if (productUnitService.updateById(productUnitInfo)) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

    @ApiOperation(value = "删除产品单位", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "产品单位id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/delBatch")
    public JsonResult delete(String ids) {

        if (StringUtils.isNotBlank(ids)) {
            List<Long> idList = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (int i = 0; i < idArray.length; i++) {
                idList.add(Long.valueOf(idArray[i]));
            }
            if (productUnitService.remove(new QueryWrapper<ProductUnitInfo>().in("id", idList))) {
                return JsonResult.success("删除成功");
            }
        } else {
            return JsonResult.fail("请选择数据");
        }

        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询所有产品单位(不分页)", notes = "查询所有产品单位(不分页)")
    @GetMapping("/getAll")
    public JsonResult<ProductUnitInfo> getAll() {

        QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
        List<ProductUnitInfo> productUnitInfoList = productUnitService.list(wrapper);
        return JsonResult.success(productUnitInfoList);
    }

    @ApiOperation(value = "查询产品单位", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productUnitId", value = "id", required = true, dataType = "Long", paramType = "query")
    })
    @GetMapping("/getProductUnitById")
    public JsonResult<ProductUnitInfoVO> getProductUnitById(Long productUnitId) {

        ProductUnitInfoVO unitVO = productUnitService.get4appById(productUnitId);
        return JsonResult.success(unitVO);
    }

    @GetMapping("/getProductUnitByType")
    public JsonResult getProductUnitByType(@RequestParam Integer type, Long productTypeId) {

        QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        wrapper.eq("product_type", productTypeId);
        wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
        List<ProductUnitInfo> productUnit = productUnitService.list(wrapper);
        return JsonResult.success(productUnit);
    }

    @GetMapping("/countByProductType")
    public JsonResult countByProductType(Long productType) {

        Integer count = productUnitService.count(new QueryWrapper<ProductUnitInfo>().eq("product_type", productType).eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise));
        return JsonResult.success(count);
    }


    @ApiOperation(value = "查询所有产品单位(不分页)", notes = "查询所有产品单位(不分页)")
    @GetMapping("/getAllUnit")
    public JsonResult<ProductUnitInfo> getAllUnit(@RequestParam Integer type) {

        QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        wrapper.select("id", "name");
        wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
        List<ProductUnitInfo> productUnitInfoList = productUnitService.list(wrapper);
        return JsonResult.success(productUnitInfoList);
    }

    @ApiOperation(value = "查询产品的基础单位", notes = "查询产品的基础单位")
    @GetMapping("/getIsBaseUnitProductUnitByType")
    public JsonResult getIsBaseUnitProductUnitByType(@RequestParam Integer type, Long productTypeId) {

        QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        wrapper.eq("product_type", productTypeId);
        wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
        wrapper.eq("is_base_unit", "1");
        ProductUnitInfo productUnitInfo = productUnitService.getOne(wrapper);
        return JsonResult.success(productUnitInfo);
    }

    @ApiOperation(value = "查询平台的所有产品单位", notes = "查询平台的所有产品单位")
    @GetMapping("/platformProductUnitList")
    public JsonResult platformProductUnitList() {
        System.out.println(111);
        return platformClient.platformProductUnitList();
    }
}
